#include "videothread.h"
#include <QSemaphore>

extern volatile bool isSavePic;
extern volatile bool isSaveVideo;
extern QSemaphore semPic;
extern QSemaphore semVideo;

VideoRecordThread::VideoRecordThread(VideoDevice* vd)
{
    this->vd = vd;
    isStop = false;
}

VideoRecordThread::~VideoRecordThread()
{

}

void VideoRecordThread::stop()
{
    isStop = true;
    quit();
    wait();
}

void VideoRecordThread::run()
{
    qDebug()<<"video thread!";
    while(1)
    {
        msleep(5);
        if(isStop == true) {
            return;
        }
        if(vd == nullptr) {
            continue;
        }
        if (isSaveVideo) {
            semVideo.acquire();

            VideoEncode::write(vd->yuv_buffer, vd->yuv_buffer_len);
        }
    }
}

PictureRecordThread::PictureRecordThread(VideoDevice* vd)
{
    this->vd = vd;
    isStop = false;
}

PictureRecordThread::~PictureRecordThread()
{

}

void PictureRecordThread::stop()
{
    isStop = true;
    quit();
    wait();
}

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <sys/time.h>

#include "videoffmpeg.h"

using namespace cv;

void PictureRecordThread::run()
{
    qDebug()<<"picture thread!";
    VideoFfmpeg::init();
    while(1)
    {
        usleep(1000*30);
        if(isStop == true) {
            return;
        }
        if(vd == NULL) {
            continue;
        }
        if (isSavePic) {
            qDebug()<<"isSavePic";
            semPic.acquire();
            int w = vd->get_width();
            int h = vd->get_height();
#if 0
            //16ms
            cv::Mat yuvBuf(h, w, CV_8UC2, vd->yuv_buffer);
            cv::Mat rgbBuf;
            cvtColor(yuvBuf, rgbBuf, COLOR_YUV2RGB_YVYU);

            cv::imwrite("/usr/app/zhangya/111.jpg", rgbBuf);
            //QImage image = QImage((unsigned char *)(rgbBuf.data), rgbBuf.cols,rgbBuf.rows, QImage::Format_RGB888).rgbSwapped();
            //image.save("/usr/app/zhangya/111.jpg");
#else
            struct timeval tpend1, tpend2;
            long msec1 = 0;
            gettimeofday(&tpend1, NULL);
            //77ms左右
            VideoFfmpeg::play(vd->yuv_buffer, w, h);
            gettimeofday(&tpend2, NULL);
            msec1 = 1000 * (tpend2.tv_sec - tpend1.tv_sec) + (tpend2.tv_usec - tpend1.tv_usec) / 1000;
            qDebug()<<"timer ms= "<<msec1;
#endif
            isSavePic = false;
        }
    }
}
